/*
	DivBox v2.0
	Website: http://jquery.phpbasic.com
	Download: http://code.google.com/p/divbox
	Visit http://code.google.com/p/divbox/source/browse/trunk/divbox/divbox.js for lastest version.
	Released under the MIT, BSD, and GPL Licenses
*/
(function($){

	$.fn.divbox = function(opt,obj){
		var _cfg = {
			width: null, 
			height: null,
			skin: null,
			speed: 500,
			animate:  'default', // currently we are only support: default &  explore & scroll & none
			animate_begin: true,
			animate_close: true,
			left: null,
			top: null,
			type: null,
			src: 'href',
			embed: null,
			scrollbar: 'auto',
			btn_closed: '#divbox_frame .closed',
			btn_prev: '#divbox_frame .prev',
			btn_next: '#divbox_frame .next',
			btn_number: '#divbox_frame .number',
			btn_slidecontrol: '#divbox_frame .slide_control',
			path: 'players/',
			full_drag_handle: false,
			resize_large_image: true,
			click_full_image: true,
			overlay: true,
			caption: true,
			caption_control: true,
			caption_number: true,
			event: 'click',
			slide: 2000, // null: disable slide, <int> the time of slide
			container: 'body',
			download_able:['pdf','zip','gz','rar','doc','docx','xls','xslx','ppt','pptx','csv'],
			languages: {
				btn_close: 'Close',
				btn_next: 'Next',
				btn_prev: 'Prev',
				click_full_image: 'Click on here to view full image',
				error_not_youtube: 'This is not a youtube link',
				error_not_vimeo: 'This is not a vimeo link',
				error_cannot_load: "We can't load this page\nError: "
			},
			api:{
				start: null,
				beginLoad: null,
				afterLoad: null,
				closed: null
			}
			
		};
		if(opt) $.extend(_cfg,opt);
		var dxMatch = [];
		var clickobj = $(this).offset();
		if(_cfg.event == 'call'){
			dxMatch[0] = obj;
			var $dx = new dx(_cfg,dxMatch,clickobj);
			$dx.load(0,1);
			return false;
		}else{
			$(this).each(function(i,o){
				dxMatch[i] = o;
			});
			
			$(this).unbind('click').bind('click',function(){
				var $dx = new dx(_cfg,dxMatch,clickobj);
				for(var i in dxMatch) if(dxMatch[i] === this){ $dx.load(i*1,1); }
				return false;
			});
		}
		return false;
	};


	var dx = function(_cfg,dxMatch,_click){
		var sizesystem = pageSize();
		var timeout = null;
		var fn = this; 
		this.idx = 0;
		this.caption = '';
		this.close = function(){
			if(timeout) clearTimeout(timeout);
			$('#divbox_frame').dxAnimate({
				enable: _cfg.animate_close,
				width: 10, 
				height: 10,
				top: _click.top,
				left: _click.left
			},_cfg.speed,function(){
				$('#divbox').remove();
				$('#divbox_frame').remove();
			});
		};
		this.setval = function(cond, val1, val2){
			return cond ? val1 : val2;
		};
		this.init = function(){
			var requires  = '#divbox,#divbox_frame,#divbox_content,#divbox_ajax';
			$(requires).remove();
			var browserinfo = browserInfo();
			$(_cfg.container).css({position: 'relative'}).prepend('<div id="divbox"></div><div id="divbox_ajax"></div><div id="divbox_frame" class="'+(_cfg.skin?_cfg.skin:'divbox_default')+' '+(browserinfo.is_mac?'mac':'')+'"><div class="closed" title="'+_cfg.languages.btn_close+'"></div><div id="divbox_data"><div id="divbox_content"></div><div class="prev" title="'+_cfg.languages.btn_prev+'"></div><div class="caption"></div><div class="slide_control" style="display:none;"></div><div class="number">0/0</div><div class="next" title="'+_cfg.languages.btn_next+'"></div></div></div>');
			if(_cfg.overlay){
				$('#divbox').css({
					width: sizesystem[0]+'px',
					height: sizesystem[1]+'px',
					position:'absolute',
					zIndex:'10001',
					left:'0',
					top:'0'
				}).click(function(){
					fn.close();
				});
			}
			$('#divbox_frame').css({
				position:'absolute',
				top: _click.top,
				left: _click.left,
				zIndex:'10002',
				width: 0,
				height: 0
			}).dxAnimate({
				enable: _cfg.animate_begin && _cfg.animate != 'none',
				width: 50, 
				height: 50,
				top: _cfg.top?sizesystem[3] +  _cfg.top: sizesystem[3] + Math.round(sizesystem[5]/2),
				left: _cfg.left?sizesystem[2] +_cfg.left:Math.round(sizesystem[4]/2) 
			},_cfg.speed);
			
			
			
		};
		this.resizeWindow = function(){
			var sizesystem = pageSize();
			$('#divbox').css({
				'width': sizesystem[0]+'px',
				'height': sizesystem[1]+'px'
			});
			var oFrame = $('#divbox_frame');
			var w = $(oFrame).outerWidth();
			var h = $(oFrame).outerHeight();
			$(oFrame).css({
				top: _cfg.top?sizesystem[3] +  _cfg.top: sizesystem[3] + Math.round((sizesystem[5] - h)/2),
				left:  _cfg.left?sizesystem[2] +_cfg.left:Math.round((sizesystem[4] - w)/2) 
			});
		};
		
		this.next = function(){
			if(timeout) clearTimeout(timeout);
			if(fn.idx < dxMatch.length - 1){
				fn.load(fn.idx+1);
			}
		};
		
		this.prev = function(){
			if(timeout) clearTimeout(timeout);
			if(fn.idx > 0) fn.load(fn.idx-1);
		};
		
		this.repair = function(){
			$(document).unbind('keydown');
			$('#divbox_content').html('');
			$(_cfg.btn_slidecontrol).removeClass('slide_control_disabled');
			$(_cfg.btn_closed+','+_cfg.btn_next+','+_cfg.btn_prev+','+_cfg.btn_number+','+_cfg.btn_slidecontrol+',#divbox_frame .caption').hide();
		};
		
		this.load = function(idx,initcall){
			
			
			var obj = dxMatch[idx];
			fn.idx = idx;
			//$(_cfg.btn_close+','+_cfg.btn_prev+','+ _cfg.btn_next+','+_cfg.btn_caption+','+_cfg.btn_number).hide();
			var src = $(obj).attr(_cfg.src).toString();
			//document.title = idx+' '+dxMatch.length+' '+Math.random()+ ' '+src;
			var ext = fn.parseExt(src);
			for(var i in _cfg.download_able) if(ext==_cfg.download_able[i]){
				window.open(src);
				return false;
			}
			
			if(initcall) fn.init();
			fn.repair();
			//var caption = '';
			if(typeof(_cfg.caption)=='function'){
				fn.caption = _cfg.caption(obj);
			}else if(_cfg.caption === true){
				fn.caption = $(obj).attr('title');	
			}
			
			
			switch(ext){
				case 'jpg':
				case 'jpeg':
				case 'gif':
				case 'png': fn.viewImage(src);break;
			}
			
		};
		this.slide_pause = function(){
			if(timeout) clearTimeout(timeout);
		};
		this.slide_start = function(){
			fn.slide_pause();
			if(_cfg.slide){ // auto slide
				if(fn.idx < dxMatch.length - 1){
					
					timeout = setTimeout(function(){fn.next();},_cfg.slide);
				}else{
					if(timeout) clearTimeout(timeout);
				}
			}
		};
		this.main = function(t,l,w,h,fncallback){
			var oContent = $('#divbox_content');
			var oFrame = $('#divbox_frame');
			$('#divbox_data').css({width: w, height: h});
			oContent.closed = function(){ fn.closed();};
			oContent.resize = function(w,h){ fn.resize(w,h);};
			if(typeof(_cfg.api.beginLoad)=='function') _cfg.api.beginLoad(oContent);
			if(typeof(fncallback) == 'function') fncallback(oContent);
			if(typeof(_cfg.api.afterLoad) == 'function') _cfg.api.afterLoad(oContent);
		
			$(_cfg.btn_closed).show().click(function(){
				//if(typeof(fnclosed) == 'function') fnclosed(oContent);
				fn.close();
			});
			$('#divbox').bind('click',function(){
				//if(typeof(fnclosed) == 'function') fnclosed(oContent);
				fn.close();
			});
			
			$(oFrame).addClass('white').css({margin: 0});
			
			var c = $(oFrame).find('.caption').html(fn.caption);
			
			if(_cfg.caption != false && (fn.caption != '' || _cfg.caption_control == true)){
				var cH = c.outerHeight(true);
				$('#divbox_data').css({height: h+ cH});
				$(oFrame).animate({'enable': true,height: h + cH}).find('.caption').show();
				
				if(_cfg.caption_control == true){// caption control
					var btn_top = h + cH/2 - 12;//parseInt(c.css('padding-top')); // 12 = 1/2 height of button prev/next icon
					var total = dxMatch.length;
					$(_cfg.btn_prev+','+_cfg.btn_next+','+_cfg.btn_number+','+_cfg.btn_slidecontrol).css({top: btn_top}).show();
					if(fn.idx>0){
						$(_cfg.btn_prev).removeClass('prevDisabled').unbind('click').bind('click',function(){
							fn.prev();
						});
					}else{
						$(_cfg.btn_prev).addClass('prevDisabled').unbind('click');		
					}
					if(_cfg.caption_number){
						$(_cfg.btn_number).html((fn.idx+1)+'/'+total);
					}else{
						$(_cfg.btn_number).remove();
					}
					
					$(_cfg.btn_slidecontrol).unbind('click').bind('click',function(){
						var is_disable = $(this).hasClass('slide_control_disabled');
						if(is_disable){
							$(this).removeClass('slide_control_disabled');
							fn.slide_start();
							
						}else{
							$(this).addClass('slide_control_disabled');
							fn.slide_pause();
						}
						
					});
					if(fn.idx<total - 1){
						$(_cfg.btn_next).removeClass('nextDisabled').unbind('click').bind('click',function(){
							fn.next();
						});
					}else{
						$(_cfg.btn_next).addClass('nextDisabled').unbind('click');	
					}
				}else{ // have no caption control
					$(c).css({'padding-left': '5px', 'padding-right': '5px'});		
				}	
			}
			$(document).bind('keydown',function(e) {
				var k = e?e.keyCode:event.keyCode;
				if(k == 27){
					if(typeof(fnclosed) == 'function') fnclosed($('#divbox_content'));
					fn.close();
				}
				if(_cfg.caption != '' && _cfg.caption_control==true){
					if(k == 38 || k==39){ fn.next(); return false; }
					if(k == 37 || k==40){ fn.prev(); return false; }
				}
			});
			
			try {
				var drag_handle = _cfg.caption == false?'#divbox_frame':'#divbox_frame .caption';
				$("#divbox_frame").draggable({ handle: $(drag_handle) }).css({ cursor: 'move' });
				if(!_cfg.full_drag_handle) $('#divbox_content').css({ cursor: 'pointer' });
			} catch(e) { /* requires jQuery UI draggables */ }
			
			$(window).bind('resize scroll',function(){
				fn.resizeWindow();
			});
			
			fn.slide_start();
			
			
		};
		
		this.animate = function(t,l,w,h, callback){
			var oFrame = $('#divbox_frame');
			var _l =  fn.setval(_cfg.left,_cfg.left,l);
			var _w = fn.setval(_cfg.width,_cfg.width,w);
			var _t = fn.setval(_cfg.top,_cfg.top + sizesystem[3] ,t);
			var _h = fn.setval(_cfg.height,_cfg.height,h);
			if(_cfg.animate == 'default'){
				$(oFrame).removeClass('white').animate({
					left: _l,
					width: _w
				},_cfg.speed).animate({
					top: _t, 
					height: _h
				},_cfg.speed,function(){  fn.main(t,l,w,h,callback);});
			}else if(_cfg.animate == 'explore'){
				$(oFrame).removeClass('white').animate({
					left:_l,
					width:_w,
					top: _t, 
					height: _h
				},_cfg.speed,function(){ fn.main(t,l,w,h,callback);});
			}else if(_cfg.animate == 'scroll'){
				$(oFrame).removeClass('white').animate({
					left: _l,
					top: _t
				},_cfg.speed).animate({
					width: _w
				},_cfg.speed).animate({
					height: _h
				},_cfg.speed,function(){ fn.main(t,l,w,h,callback);});
			}else if(_cfg.animate == 'none'){
				$(oFrame).removeClass('white').css({
					left:_l,
					top: _t,
					width:_w,
					height: _h
				}).fadeIn(_cfg.speed,function(){ fn.main(t,l,w,h,callback);});
			}
			
		};
		this.viewImage = function(src,caption){
			var Img = new Image();
			Img.onerror = function(){
				//fn.error('This image cannot download!');
				alert('This image cannot download');
			};
			Img.onload = function(){
				//$('#divbox_content').html('<img src="'+src+'" style="display:none" />');
				var imgW = Img.width;
				var imgH = Img.height;
				imgW = fn.setval(_cfg.width,_cfg.width,imgW);
				imgH = fn.setval(_cfg.height,_cfg.height,imgH);
				var zoom = 0;
				if(_cfg.resize_large_image){
					if(imgW >= sizesystem[4] - 100 || imgH >= sizesystem[5] - 100 || Img.width > imgW || Img.height > imgH){
						if(imgW >= sizesystem[4] - 100 ){
							imgW = sizesystem[4] - 100;
							imgH = Math.round(imgW*Img.height/Img.width);
						}
						if(imgH >= sizesystem[5] - 100){
							tH = sizesystem[5] - 100;
							imgW = Math.round(imgW*tH/imgH);
							imgH = tH;
						}
						if(_cfg.click_full_image) zoom = 1;
					}
				}
				
				
				
				var top = sizesystem[3] + Math.round((sizesystem[5] - imgH)/2);
				var left = Math.round((sizesystem[4] - imgW)/2);
				
				fn.animate(top,left,imgW,imgH,function(o){
					var ie6 = ($.browser.msie && parseInt($.browser.version) == 6)?true:false;
					if(ie6 && ext == 'png'){
						$(o).find('img').wrap('<span style="display:inline-block;width: '+imgW+'px;height: '+imgH+'px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+src+');"></span>');
					}else{
						$(o).html('<img src="'+src+'" />').find('img').css({width: imgW,height: imgH,display:'block'}).fadeIn();
					}
					if(zoom) $(o).find('img').addClass('zoom').attr({'title': _cfg.languages.click_full_image}).click(function(){
						window.open(src,'wDivBox');
					});
				});
				Img.onload = function(){};
			};
			Img.src = src;
		};
		
		this.parseExt = function(src){
			if(typeof(_cfg.embed) == 'string') return 'embed';
			if(_cfg.type) return _cfg.type;
			if (src.match(/youtube\.com\/watch/i)){
				return 'youtube';
			}
			if (src.match(/vimeo\.com\/(\d+)/i)){
				return 'vimeo';
			}
			var aExt = src.split('.');
			var ext = aExt[aExt.length-1];
			return ext.toLowerCase();
		};
		
	};
	
	
	
	// interface 
	$.divbox = function(arg,opt){
		if(!opt) var opt = {};
		if(typeof(arg) == 'object'){
			opt.event = 'call';
			$(arg).divbox(opt,arg);
		}else if(typeof(arg) == 'string'){
			var obj = {'href': arg};
			opt.event = 'call';
			opt.src = 'href';
			$('body').divbox(opt,obj);
		}else if(typeof(arg) == 'undefined'){
		}
		
		this.close = function(){
			var $dx = new dx({},[],{top: 0, left: 0});
			$dx.close();
		};
		this.alert = function(str, title, fn){
			
		};
		this.confirm = function(){
			
		};
		this.prompt = function(){
			
		};
		this.tooltip = function(){
			
		};
		return this;
		
	};
	$.fn.dxAnimate = function(obj,time, fn){
		if(obj.enable === true){
			$(this).animate(obj,time,fn);
		}else{
			$(this).css(obj);
			if(typeof(fn)=='function') fn();
		}
		return this;
	};
	
	function pageSize(){
		var de = document.documentElement;
		var winW = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		var winH = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		var x = window.pageXOffset || self.pageXOffset || (de&&de.scrollLeft) || document.body.scrollLeft;
		var y = window.pageYOffset || self.pageYOffset || (de&&de.scrollTop) || document.body.scrollTop;
		var pW = window.innerWidth || document.body.scrollWidth || document.body.offsetWidth;
		var pH = window.innerHeight+window.scrollMaxY || document.body.scrollHeight || document.body.offsetHeight;
		var w = Math.max(winW,pW); 
		var h = pH<winH?winH:pH;
		arrayPageSize = [w,h,x,y,winW,winH];
		return arrayPageSize;
	}
	function browserInfo(){
		is_mac = false;
		if (navigator.platform.toLowerCase().indexOf('mac') != -1 || navigator.platform.toLowerCase().indexOf('ios') != -1 || navigator.platform.toLowerCase().indexOf('iphone') != -1) is_mac = true;
		return {
			is_mac: is_mac
		};
	}
})(jQuery);